﻿using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json.Linq;
using Sparklings.JsonUtils;
using Sparklings.RayTracing;
using System.Collections.Generic;

namespace Sparklings.LevelElements
{
    public class Spawner : Tile, IActivable
    {
        public RayColor SpawnedColor;
        public int SparklingsLeftCount { get; private set; }
        public Spawner(Level level, int x, int y, int totalSpawnableSparklings, RayColor spawnedColor = RayColor.None)
            : base(level, x, y, false)
        {
            SparklingsLeftCount = totalSpawnableSparklings;
            SpawnedColor = spawnedColor;
        }
        public override void LoadGraphicsRelatedElements()
        {
            base.LoadGraphicsRelatedElements();
            BaseTexture = Level.ContentManager.Load<Texture2D>("spawner");
        }
        public override void DrawBase(Rendering.RenderContext rc)
        {
            base.DrawBase(rc);
        }
        public override void DrawText(Rendering.RenderContext rc, SpriteBatch b)
        {
            base.DrawText(rc, b);
            b.DrawString(Level.Font, SparklingsLeftCount.ToString(), rc.ToScreenPosition(PositionULCorner), SpawnedColor.ToColor());
        }
        public override JToken GetJsonData(JsonOverrider converter)
        {

            var ret = new JObject();
            ret["color"] = converter.Write(SpawnedColor);
            ret["left"] = converter.Write(SparklingsLeftCount);
            return ret;
        }
        public static object ConstructFromData(JsonOverrider converter, JToken toConvert, Level level, int x, int y)
        {
            return new Spawner(
                level,
                x, y,
                converter.Read<int>(toConvert["left"]),
                converter.Read<RayColor>(toConvert["color"]));
        }
        public override bool IsPassableBySparkling(Sparkling c) { return true; }
        public bool Activate()
        {
            if (GetCurrentlyContainedSparklings().Count == 0 && SparklingsLeftCount != 0)
            {
                Level.Sparks.Add(new Sparkling(Level, X, Y, SpawnedColor));
                --SparklingsLeftCount;
                return true;
            }
            return false;
        }

        public bool IsPlayerActivable { get; set; }

        public List<int> ActivatingInterruptors { get; set; }
    }
}
